package com.rykj.energy.task.capture.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.rykj.energy.common.enums.StateType;
import com.rykj.energy.common.utils.*;
import com.rykj.energy.database.pojo.BasicCamera;
import com.rykj.energy.database.pojo.BasicCameraPresetting;
import com.rykj.energy.database.pojo.MessageResult;
import com.rykj.energy.database.pojo.vo.CaptureParamVo;
import com.rykj.energy.database.service.ICameraPresettingService;
import com.rykj.energy.database.service.ICameraService;
import com.rykj.energy.database.service.IMsgResultService;
import com.rykj.energy.task.capture.service.ICaptureService;
import lombok.extern.slf4j.Slf4j;
import net.anumbrella.seaweedfs.core.FileTemplate;
import net.anumbrella.seaweedfs.core.file.FileHandleStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.util.Date;

@Service("captureService")
@Slf4j
public class CaptureServiceImpl implements ICaptureService {

    public static String CACH_CAPTURE_IMG_KEY = "cach_capture_img_key";

    @Autowired
    private IMsgResultService msgResultService;

    @Autowired
    private ICameraService cameraService;

    @Autowired
    private ICameraPresettingService cameraPresetService;

    @Resource
    @Lazy
    private RedisUtil redisUtil;

    @Autowired
    @Lazy
    private FileTemplate template;

    @Value("${file.upload:/data/rykj-energy/images}")
    private String savePicturePath;

    @Value("${ffmpeg.exe.path:ffmpeg}")
    private String ffmpegExePath;

    @Override
    public void exeCapturePlan(CaptureParamVo captureParam) {
        log.info("===抓图任务执行中~~~~~~~~~~~~~~~");
        try {
            MessageResult msgResult = new MessageResult();
            BasicCamera camera = cameraService.findById(captureParam.getCameraId());
            if(StringUtils.isNotEmpty(captureParam.getPresetId())&& !"0".equals(captureParam.getPresetId()+"")){
                //TODO 预置位编号不为空，需要调用接口先将摄像头转动到该预置位 才去抓图
                BasicCameraPresetting cameraPreset =cameraPresetService.findById(captureParam.getPresetId());
                msgResult.setPresetCode(cameraPreset.getPresettingCode());
                if(!cameraService.sdkPresetPoint(cameraPreset.getCameraNo(),cameraPreset.getPresettingCode())){
                    log.error("通道id"+cameraPreset.getCameraNo()+"_预置点编号:"+cameraPreset.getPresettingCode()+" 操作失败");
                }
            }

            if(StringUtils.isEmpty(camera.getRtspUrl())){
               String rtspUrl= cameraService.saveRtspUrlByCameraInfo(camera);
                camera.setRtspUrl(rtspUrl);
                cameraService.updateCamera(camera,null);
            }
            captureParam.setRtspUrl(camera.getRtspUrl());

            String picName = ShortUUID.generateShortUuid()+System.currentTimeMillis()+".jpg";
            //ffmpeg抓图
            String picPath=savePicturePath + File.separator + DateUtils.getDateToDay(new Date()) + File.separator + captureParam.getTaskCode();
            FFmpegUtils.getCaptureByRtsp(ffmpegExePath,captureParam.getRtspUrl(),picPath,picName);
            File file = new File(picPath + File.separator + picName);
            FileHandleStatus fileHandle = template.saveFileByStream(picName, new FileInputStream(file));
            log.info("===上传文件服务器返回结果==="+ JSONObject.toJSONString(fileHandle));
            getMsgResult(msgResult,captureParam);
            msgResult.setImageUrl(fileHandle.getFileUrl());
            msgResult.setCameraName(camera.getCamAlias());
            msgResult.setCameraNo(camera.getCamNo());
//            if(StringUtils.isNotEmpty(captureParam.getRectSeat())){
//                msgResult.setCutImgUrl(cutImgByRectSeat(fileHandle.getFileUrl(),captureParam.getRectSeat(),captureParam.getTaskCode(),null));
//            }
            msgResultService.saveMsgResult(msgResult);
            JSONObject redisObj =new JSONObject();
            redisObj.put("resultId",msgResult.getId());
            redisObj.put("picPath",picPath + File.separator + picName);
            //缓存抓取记录
            redisUtil.lLeftSet(CACH_CAPTURE_IMG_KEY,JSONObject.toJSONString(redisObj));
            //删除临时图片
//            file.delete();
        } catch (Exception e) {
            log.error("===图片抓取失败,info:" + JSONObject.toJSONString(captureParam),e);
        }
    }

    private  void getMsgResult(MessageResult msgResult,CaptureParamVo captureParam){
        msgResult.setCameraId(captureParam.getCameraId());
        msgResult.setMeterId(captureParam.getMeterId());
        msgResult.setOrgId(captureParam.getOrgId());
        msgResult.setTaskId(captureParam.getTaskId());
        msgResult.setMsgType(captureParam.getTaskCode());
        msgResult.setOrgName(captureParam.getOrgName());
        msgResult.setMsgTypeCn(captureParam.getTaskCn());
        msgResult.setCheckState("N");
        msgResult.setDealState(StateType.UNDEAL.getCode());
        msgResult.setWarningSigns("Y");
        msgResult.setMsgLevel("1");
        msgResult.setSourceType("computeAI");
        msgResult.setCreateDate(new Date());
    }
}
